package com.newworld.dmsapp2.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.litepal.crud.DataSupport;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.defect.SingleMediaScanner;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.LoginActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.MainSettingFragment;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.GetFileSize;
import com.newworld.dmsapp2.util.MyPreference;
/*import cn.jpush.android.api.JPushInterface;
 import cn.jpush.android.api.TagAliasCallback;*/

public class SettingCacheActivity extends BaseActivity implements
		OnClickListener {
	private ImageButton titlebar_left_cache_pic, clean_pic, clean_record,
			clean_data;
	public static TextView pic_inf;
	public static TextView record_inf;
	private Button clean_all;
	protected Context context;
	public static long l1 = 0, l2 = 0, k = 0;

	// private ProgressBar logInBar;
	private static final int MSG_SUCCESS1 = 0;// progressBar显示
	private static final int MSG_SUCCESS2 = 1;// progressBar隐藏
	private static final int MSG_SUCCESS3 = 2;// 显示对话框及progressBar隐藏
	private final static String PHOTO_PATH = Config.IMAGE_PATH;
	private final static String VOICE_PATH = Config.VOICE_PATH;
	public static final String action = "jason.broadcast.action";
	Handler mHandler = new Handler() {
		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {

			case MSG_SUCCESS1:

				// logInBar.setVisibility(View.VISIBLE);
				break;

			case MSG_SUCCESS2:

				// logInBar.setVisibility(View.INVISIBLE);
				Toast.makeText(SettingCacheActivity.this, "清理成功",
						Toast.LENGTH_SHORT).show();
				// init_records();
				// clean_all.set
				// pic_inf.setText("0MB");
				init_pics();
				init_records();
				GetFileSize g1 = new GetFileSize();
				k = l1 + l2;
				clean_all.setText("一键清除所有（" + g1.FormetFileSize(k) + ")");
				break;

			case MSG_SUCCESS3:
				// logInBar.setVisibility(View.INVISIBLE);
				AlertDialog.Builder builder = new AlertDialog.Builder(
						SettingCacheActivity.this);
				// 添加按钮的单击事件
				// 设置显示信息
				builder.setTitle("缓存管理")
						.setMessage("清除成功，现将跳转至登陆界面")
						.
						// 设置确定按钮
						setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									// 单击事件
									public void onClick(DialogInterface dialog,
											int which) {
										// 跳转界面
										MyPreference.getInstance(context)
												.setUserId(0);
										Intent intent = new Intent();
										intent.setClass(
												SettingCacheActivity.this,
												LoginActivity.class);
										intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(intent);
										return;
									}
								}).show();

			}
			super.handleMessage(msg);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_cache);

		initViews();
		initEvents();

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.titlebar_left_cache_pic:
			GetFileSize g6 = new GetFileSize();
			k = l1 + l2;
			 clean_all.setText("一键清除所有（"+g6.FormetFileSize(k)+")");
			MainSettingFragment.init(g6.FormetFileSize(k));
			onBackPressed();
			//finish();
			/*
			 * Intent intent1 = new Intent();
			 * intent1.setClass(SettingCacheActivity.this,
			 * SettingActivity.class); startActivity(intent1);
			 */
			break;
		case R.id.clean_pic:
			// 标准的对话框封装
			final CustomDialog dialog = new CustomDialog(
					SettingCacheActivity.this);
			dialog.setTitle("删除信息");
			dialog.setDetial("是否删除图片信息");
			dialog.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
			dialog.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					 init_pics();
					new Thread(deletePicture).start();
					 init_pics();
					 init_records();
					// clean_all.set
					 pic_inf.setText("0MB");
					 init_pics();
					 init_records();
					GetFileSize g = new GetFileSize();
					k = l1 + l2;
					clean_all.setText("一键清除所有（" + g.FormetFileSize(k) + ")");

					/*
					 * Intent intent = new Intent(action);
					 * intent.putExtra("data", g.FormetFileSize(k)+"");
					 * sendBroadcast(intent);
					 */
					// finish();

					dialog.dismiss();
				}
			});
			dialog.show();
			// ----------//

			break;

		case R.id.clean_record:
			// 标准的对话框封装
			final CustomDialog dialog1 = new CustomDialog(
					SettingCacheActivity.this);
			dialog1.setTitle("删除");
			dialog1.setDetial("是否确定删除录音信息");
			dialog1.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog1.dismiss();
				}
			});
			dialog1.show();
			dialog1.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					init_records();
					new Thread(deleteVoice).start();

					  init_pics();
					  init_records(); 
					  GetFileSize g1 = new GetFileSize();
					  k = l1 + l2;
					  clean_all.setText("一键清除所有（"+g1.FormetFileSize(k)+")");
					 // record_inf.setText("0MB");
					dialog1.dismiss();
				}
			});
			dialog1.show();
			// ----------//

			break;

		case R.id.clean_data:
			// 标准的对话框封装
			final CustomDialog dialog2 = new CustomDialog(
					SettingCacheActivity.this);
			dialog2.setTitle("删除");
			dialog2.setDetial("是否确定删除数据库信息");
			dialog2.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog2.dismiss();
				}
			});
			dialog2.show();
			dialog2.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {

					new Thread(deleteDataR).start();
					init_pics();
					init_records(); 
					GetFileSize g1 = new GetFileSize();
					k = l1 + l2;
					clean_all.setText("一键清除所有（"+g1.FormetFileSize(k)+")");
				    //data_inf.setText("0MB");
					dialog2.dismiss();
				}
			});
			dialog2.show();
			// ----------//

			break;
		case R.id.clean_all:
			// 标准的对话框封装
			final CustomDialog dialog3 = new CustomDialog(
					SettingCacheActivity.this);
			dialog3.setTitle("删除信息");
			dialog3.setDetial("是否确定删除所有缓存信息");
			dialog3.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog3.dismiss();
				}
			});
			dialog3.show();
			dialog3.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {

					new Thread(deleteAll).start();

					init_pics();
					init_records();

					GetFileSize g2 = new GetFileSize();
					k = l1 + l2;
					clean_all.setText("一键清除所有（" + g2.FormetFileSize(k) + ")");

					
					 pic_inf.setText("0MB"); record_inf.setText("0MB");
					 //data_inf.setText("0MB");
					 
					MyPreference.getInstance(context).setUserId(0);
					Intent intent = new Intent();
					intent.setClass(SettingCacheActivity.this,
							LoginActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					dialog3.dismiss();
				}
			});
			dialog3.show();
			// ----------//

			break;
		default:
			break;
		}
	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		titlebar_left_cache_pic = (ImageButton) findViewById(R.id.titlebar_left_cache_pic);
		clean_pic = (ImageButton) findViewById(R.id.clean_pic);
		clean_record = (ImageButton) findViewById(R.id.clean_record);
		clean_data = (ImageButton) findViewById(R.id.clean_data);
		pic_inf = (TextView) findViewById(R.id.pic_inf);
		record_inf = (TextView) findViewById(R.id.record_inf);
		clean_all = (Button) findViewById(R.id.clean_all);

		// 图片，录音信息初始化加载
	    GetFileSize g = new GetFileSize(); 
		long startTime = System.currentTimeMillis();
		try {
			init_pics();
			init_records();
			
			GetFileSize g3 = new GetFileSize();
			k = l1 + l2;
			clean_all.setText("一键清除所有（" + g3.FormetFileSize(k) + ")");

		} catch (Exception e) {
			e.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
		System.out.println("总共花费时间为：" + (endTime - startTime) + "毫秒...");

		// 文字信息初始化，加载

		// 初始化时，读取图片录音文件大小
		/*
		 * 通过channel来获取图片大小，与下面流读取的方法区别：File的length()方法返回的类型为long，
		 * long型能表示的正数最大值为：9223372036854775807，折算成最大能支持的文件大小 为：8954730132868714
		 * EB字节，然而FileInputStream的avaliable()方法返回值是int，在之前也介
		 * 绍了最大的表示范围，所能支持的最大文件大小为：1.99GB； 本方法没有容量上限
		 */
		/*
		 * String path = PHOTO_PATH+"text1.jpg"; FileChannel fc= null; try {
		 * File f= new File(path); if (f.exists() && f.isFile()){
		 * FileInputStream fis= new FileInputStream(f); fc= fis.getChannel();
		 * Log.i("size",fc.size()+""); long pic_record_length = f.length()/1000;
		 * System.out.println("文件长度："+pic_record_length+"KB");
		 * pic_record_inf.setText(pic_record_length+"KB"); }else{
		 * Log.i("message","file doesn't exist or is not a file"); } } catch
		 * (FileNotFoundException e) { Log.e("e",e+""); } catch (IOException e)
		 * { Log.e("e",e+""); } finally { if (null!=fc){ try{ fc.close();
		 * }catch(IOException e){ Log.e("e",e+""); } } }
		 */

		// 成功测试：通过FileInputStream来获取的文件大小：
		/*
		 * String path = PHOTO_PATH + "text2.jpg"; FileInputStream fis= null;
		 * try{ File f= new File(path); fis= new FileInputStream(f);
		 * System.out.println(fis.available()); long pic_record_length =
		 * f.length()/1000; System.out.println("文件长度："+pic_record_length+"KB");
		 * pic_record_inf.setText(pic_record_length+"KB");
		 * //logger.info(fis.available()); }catch(Exception e){
		 * Log.e("e1",e+""); } finally{ if (null!=fis){ try { fis.close(); }
		 * catch (IOException e) { Log.e("e2",e+""); } } }
		 */

		// 成功测试：File的length()方法
		// String path = PHOTO_PATH;
		/*
		 * String path = PHOTO_PATH+"text1.jpg"; File f= new File(path); if
		 * (f.exists() && f.isFile()){
		 * System.out.println("文件长度："+f.length()+"字节"); }else{
		 * Log.e("message","file doesn't exist or is not a file"); } long
		 * pic_record_length = f.length()/1000;
		 * System.out.println("文件长度："+pic_record_length+"KB");
		 * pic_record_inf.setText(pic_record_length+"KB");
		 */

	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub
		init_pics();
		init_records();
		titlebar_left_cache_pic.setOnClickListener(this);
		clean_all.setOnClickListener(this);
		clean_record.setOnClickListener(this);
		clean_pic.setOnClickListener(this);
		clean_data.setOnClickListener(this);
	}

	// 初始化图片
	public static void init_pics() {
		GetFileSize g4 = new GetFileSize();
		try {
			String path = PHOTO_PATH;
			File ff = new File(path);
			if (ff.isDirectory()) { // 如果路径是文件夹的时候
				System.out.println("图片文件个数           " + g4.getlist(ff));
				System.out.println("目录");
				l1 = g4.getFileSize(ff);
				System.out.println(path + "目录的大小为：" + g4.FormetFileSize(l1));
				pic_inf.setText(g4.FormetFileSize(l1));
			} else {
				System.out.println("     图片文件个数           1");
				System.out.println("文件");
				l1 = g4.getFileSizes(ff);
				System.out.println(path + "文件的大小为：" + g4.FormetFileSize(l1));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 初始化录音
	public static void init_records() {
		GetFileSize g5 = new GetFileSize();
		try {
			String path1 = VOICE_PATH;
			File ff1 = new File(path1);
			if (ff1.isDirectory()) { // 如果路径是文件夹的时候
				System.out.println("录音文件个数           " + g5.getlist(ff1));
				System.out.println("目录");
				l2 = g5.getFileSize(ff1);
				System.out.println(path1 + "目录的大小为：" + g5.FormetFileSize(l2));
				record_inf.setText(g5.FormetFileSize(l2));
			} else {
				System.out.println("     录音文件个数           1");
				System.out.println("文件");
				l2 = g5.getFileSizes(ff1);
				System.out.println(path1 + "文件的大小为：" + g5.FormetFileSize(l2));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 删除本地数据库
	 */
	private void deleteData() {
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.User.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Function.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Photo.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Task.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.RelationHouse.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.RepairApply.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.RepairNode.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Server.class);
	}

	// 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
	@SuppressLint("NewApi")
	public void deleteFilesByDirectory(File directory) {
		if (directory != null && directory.exists() && directory.isDirectory()) {
			for (File item : directory.listFiles()) {
				System.out.println("item.getAbsolutePath()>>>>>"
						+ item.getAbsolutePath());
				String fileName = item.getName();
				System.out.println(fileName);
				item.delete();
				String filePath = PHOTO_PATH
						+ fileName;
				MediaScannerConnection
						.scanFile(
								this,
								new String[] { PHOTO_PATH + fileName }, null,
								null);
				File dbFile = new File(filePath);
				new SingleMediaScanner(this, dbFile);
			}
		}
	}

	private Runnable deletePicture = new Runnable() {

		@Override
		public void run() {

			mHandler.obtainMessage(MSG_SUCCESS1).sendToTarget();
			/*
			 * deleteFilesByDirectory(new
			 * File(Environment.getExternalStorageDirectory() +
			 * File.separator+"NewWorld_download"));
			 */
			deleteFilesByDirectory(new File(PHOTO_PATH));
			mHandler.obtainMessage(MSG_SUCCESS2).sendToTarget();

		}

	};
	private Runnable deleteVoice = new Runnable() {

		@Override
		public void run() {

			mHandler.obtainMessage(MSG_SUCCESS1).sendToTarget();
			deleteFilesByDirectory(new File(VOICE_PATH));

			mHandler.obtainMessage(MSG_SUCCESS2).sendToTarget();

		}

	};
	private Runnable deleteDataR = new Runnable() {

		@Override
		public void run() {

			mHandler.obtainMessage(MSG_SUCCESS1).sendToTarget();
			List<User> users = DataSupport.findAll(User.class);
			List<String> unusedtag = new ArrayList<String>();
			if (users != null) {
				for (User uu : users) {
					unusedtag.add(uu.getUserId());
				}
			}
			// 问题：这里推送有什么用，为什么没有可导入的包
			/*
			 * JPushInterface.setAlias(SettingCacheActivity.this, "", new
			 * TagAliasCallback(){
			 * 
			 * @Override public void gotResult(int arg0, String arg1,
			 * Set<String> arg2) { // TODO Auto-generated method stub
			 * Log.d("jpush", "setAlia success when clear"+arg0); }
			 * 
			 * });
			 */
			deleteData();
			MyPreference.getInstance(getApplicationContext()).setSqlInit(false);
			MyPreference.getInstance(getApplicationContext()).setUserId(0);
			mHandler.obtainMessage(MSG_SUCCESS2).sendToTarget();

		}

	};

	private Runnable deleteAll = new Runnable() {

		@Override
		public void run() {

			mHandler.obtainMessage(MSG_SUCCESS1).sendToTarget();
			/*
			 * List<User> users = DataSupport.findAll(User.class); List<String>
			 * unusedtag = new ArrayList<String>(); if(users!=null){ for(User
			 * uu:users){ unusedtag.add(uu.getUserid());
			 * Log.e("缓存不活跃用户",uu.getUserid()); } }
			 */
			// 不使用百度推送
			// 重设极光推送
			/*
			 * JPushInterface.setAlias(Systemm2_cacheManagement.this, "", new
			 * TagAliasCallback(){
			 * 
			 * @Override public void gotResult(int arg0, String arg1,
			 * Set<String> arg2) { // TODO Auto-generated method stub
			 * Log.d("jpush", "setAlia success when clear"+arg0); }
			 * 
			 * });
			 */
			// 清除缓存
			/*
			 * deleteFilesByDirectory(new File("/data/data/" + "com.dms.app" +
			 * "/cache"));
			 */
			// 清除图片
			/*
			 * deleteFilesByDirectory(new
			 * File(Environment.getExternalStorageDirectory() +
			 * File.separator+"NewWorld_download"));
			 */
			deleteFilesByDirectory(new File(
					PHOTO_PATH));

			// 清除录音
			deleteFilesByDirectory(new File(
					VOICE_PATH));
			// 清除数据库
			deleteData();
			// 清除sharedPreference
			MyPreference.getInstance(getApplicationContext()).setSqlInit(false);
			MyPreference.getInstance(getApplicationContext()).setUserId(0);

			mHandler.obtainMessage(MSG_SUCCESS3).sendToTarget();

		}

	};

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			init_pics();
			init_records();
			GetFileSize g6 = new GetFileSize();
			k = l1 + l2;
			clean_all.setText("一键清除所有（"+g6.FormetFileSize(k)+")");
			MainSettingFragment.init(g6.FormetFileSize(k));
			onBackPressed();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
